<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\OrderProduct;
use app\common\tool\Excel;
use think\App;
use think\facade\View;
use app\common\model\Area;
use app\common\facade\Builder;
use think\exception\ValidateException;

class Order extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\Order';

    //关联模型
    protected array $hasOne = ['user', 'p', 'c', 'd'];

    //自定义方法排序
    protected array $sort = ['id' => 'desc'];

    protected int $takeOver = 3;

    public function index(): string
    {
        return Builder::Table()
            ->addColumn(['field' => 'id', 'title' => 'ID', 'sort' => true, 'width' => 90])
            ->addColumn(['field' => 'sn', 'title' => '订单编号'])
            ->addColumn(['field' => 'uid', 'title' => '相关会员', 'templet' => '#_userTpl', 'width' => 250])
            ->addColumn(['field' => 'product', 'title' => '订单商品'])
            ->addColumn(['field' => 'total_amount', 'title' => '订单金额'])
            ->addColumn(['field' => 'real_amount', 'title' => '实付金额'])
            ->addColumn(['field' => 'create_time', 'title' => '下单时间'])
            ->addColumn(['field' => 'status', 'title' => '状态'])
            ->addColumn(['field' => 'receiver', 'title' => '收货人姓名'])
            ->addColumn(['field' => 'receiver_tel', 'title' => '收货人手机号'])
            ->addColumn(['field' => 'address', 'title' => '收货地址', 'templet' => '#addressTpl', 'width' => 250])
            ->addColumn(['field' => 'pay_time', 'title' => '支付时间'])
            ->addColumn(['field' => 'pay_way', 'title' => '支付方式'])
            ->addColumn(['field' => 'post_time', 'title' => '发货时间'])
            ->addColumn(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#orderDemo', 'title' => '操作', 'width' => 220])
            ->addTopButtons(['export'])
            ->addRightButtons([
                'edit' => ['title' => '详情'],
                'deliver' => ['title' => '发货', 'url' => url('order/deliver')->build(), 'event' => '_openNewPage'],
                'delete'
            ])
            ->addSearch([
                ['uid', '会员编号/昵称/手机号', 'input', '', '\app\common\model\User', 'code|nickname|mobile,id'],
                ['sn', '订单编号', 'input'],
                ['status', '订单状态', 'select', getOrderStatus()]
            ])
            ->addJsUrl(['order'])
            ->addExtraHtml(['order'])
            ->fetch();
    }

    public function edit($id = '', $tpl = 'order/edit', $info = '')
    {
        return parent::edit($id, $tpl, $info); // TODO: Change the autogenerated stub
    }

    public function deliver($id = '')
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            try {
                $this->validate($param, 'Deliver');
            } catch (ValidateException $e) {
                return json(['code' => -1, 'msg' => $e->getError()]);
            }

            return json($this->model::deliver($param, $this->admin));
        }
        $info = $this->model::find($id);
        View::assign([
            'express' => \app\common\model\Express::where(['status' => 1, 'is_del' => 0])->select(),
            'info' => $info
        ]);

        return View::fetch();
    }

    public function getArea($id, $level = 0)
    {
        return Area::getArea($id ?: 100000, $level);
    }

    public function singleExport()
    {
        $id = $this->request->param('id');
        $map = [
            ['title' => 'ID', 'key' => 'id'],
            ['title' => '编号', 'key' => 'sn'],
            ['title' => '相关会员', 'key' => 'user_info'],
            ['title' => '订单商品', 'key' => 'product_info'],
            ['title' => '订单金额', 'key' => 'total_amount'],
            ['title' => '实付金额', 'key' => 'real_amount'],
            ['title' => '下单时间', 'key' => 'create_time'],
            ['title' => '状态', 'key' => 'status'],
            ['title' => '收货人姓名', 'key' => 'receiver'],
            ['title' => '收货人手机号', 'key' => 'receiver_tel'],
            ['title' => '收货地址', 'key' => 'address'],
            ['title' => '支付时间', 'key' => 'pay_time'],
            ['title' => '支付方式', 'key' => 'pay_way'],
            ['title' => '发货时间', 'key' => 'post_time'],
        ];
        $list = $this->model::where(['id' => $id])->select();
        foreach ($list as &$val) {
            if ($val->user) {
                $val->user_info = $val->user->code . ' - ' . $val->user->nickname . '-' . $val->user->mobile;
            } else {
                $val->user_info = '-';
            }
            $p = $val->p ? $val->p->title : '';
            $c = $val->c ? $val->c->title : '';
            $d = $val->d ? $val->d->title : '';
            $val->address = $p . $c . $d . $val->address_details;
            $product = OrderProduct::where(['order_id' => $val->id])->select();
            $val->product_info = '';
            foreach ($product as $v) {
                $val->product_info .= ' ' . $v->product_title . ' 数量：' . $v->num;
            }
            $val->pay_time = $val->pay_time ? date('Y-m-d H:i:s', $val->pay_time) : '待支付';
        }

        (new Excel())->export('订单列表', $map, $list->toArray());
    }
}